package websocket

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"github.com/gorilla/websocket"
	//"gitlab.local/TerraMaster/tos-modules/middleware"
	"log"
	"net/http"
)

type Response struct {
	IsLogin bool        `json:"is_login"`
	Code    bool        `json:"code"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
	Time    float64     `json:"time"`
	CodeNum int         `json:"code_num"`
	CodeMsg string      `json:"code_msg"`
}

type Params struct {
	ClientIP string          `json:"client_ip"`
	Name     string          `json:"name"`
	Action   string          `json:"action"`
	Data     json.RawMessage `json:"data"`
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type HandlerFunc func(*websocket.Conn, Params) (interface{}, error)

func HandleWebSocket(c *gin.Context, fnType func(mType string) HandlerFunc) {
	// 在这里检查并获取Cookie
	cookie, err := c.Request.Cookie("userName")
	if err != nil {
		log.Println("Info err:", err)
		return
	}
	if cookie.Value == "" {
		log.Println("Info err1:", err)
		return
	}
	// 升级 HTTP 连接为 WebSocket 连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("WebSocket conn fail:", err)
		return
	}
	defer conn.Close()
	params := Params{}
	params.Name = cookie.Value
	ffn := fnType("getBackgroundTaskLogs")
	if ffn != nil {
		//推送任务信息
		_, _ = ffn(conn, params)
	}

	for {
		// 读取 WebSocket 消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("Read message fail:", err)
			return
		}

		params = parseCommand(message)
		params.ClientIP = c.ClientIP()
		// 执行相应的操作
		fn := fnType(params.Action)
		if fn != nil {
			_, _ = fn(conn, params)
		}
	}
}

// 解析消息
func parseCommand(message []byte) Params {
	var command Params
	err := json.Unmarshal(message, &command)
	if err != nil {
		log.Println("Parse command fail:", err)
	}
	return command
}
